﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mimoza.Transport;
using Mimoza.Common;

namespace Mimoza.DBLayer.Transport.Server
{
    public interface IEventNotifier
    {
        void EventPublishNotify(Connection conn, DBObjectChangedEventArgs e);
    }

    public class EventSubscription : IDisposable
    {
        public EventSubscription()
        {
        }

        public EventSubscription(Connection conn, IDBObjectChangedNotfier source, IEventNotifier notifier)
        {
            m_conn = conn;
            m_notifier = notifier;
            m_source = source;

            m_source.OnObjectChanged += EventHandler;
        }

        void EventHandler(object sender, DBObjectChangedEventArgs e)
        {
            m_notifier.EventPublishNotify(m_conn, e);
        }

        public void Dispose()
        {
            m_source.OnObjectChanged -= EventHandler;
        }

        Connection m_conn;
        IEventNotifier m_notifier;
        IDBObjectChangedNotfier m_source;
    }

    public class EventManager<TRecord> : IEventNotifier
        where TRecord : class, new()
    {
        public void Subscribe(Connection conn, IDBObjectChangedNotfier source)
        {
            m_objectStore.Add(new EventSubscription(conn,source,this), conn);
        }

        public void EventPublishNotify(Connection conn, DBObjectChangedEventArgs e)
        {
            RepositoryEventRequest<TRecord> request = new RepositoryEventRequest<TRecord>(e.Object as TRecord,
                e.EventType);

            // Problem: Transport is not support two way calls by one connection
            // In that implementation of transport TransportDBLayer should create two connection 
            // (first for request, second for notify)

            //conn.SendRequest(request);
        }

        ConnectionObjectStore<EventSubscription> m_objectStore = new ConnectionObjectStore<EventSubscription>();
    }
}
